package com.lsj.config.security;

import org.jasig.cas.client.session.SingleSignOutFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.cas.web.CasAuthenticationEntryPoint;
import org.springframework.security.cas.web.CasAuthenticationFilter;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.logout.LogoutFilter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    AuthenticationEntryPoint authenticationEntryPoint;
    @Autowired
    AuthenticationProvider authenticationProvider;
    @Autowired
    SingleSignOutFilter singleSignOutFilter;
    @Autowired
    LogoutFilter logoutFilter;
    @Autowired
    CasAuthenticationFilter casAuthenticationFilter;

    /*配置 authenticationProvider，这个 authenticationProvider 实际上就是一开始配置的 CasAuthenticationProvider*/
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/user/**").hasRole("user")
                .antMatchers("/login/cas").permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling()
                //authenticationEntryPoint就是在CasConfig定义的CasAuthenticationEntryPoint
                //当发生请求时，发现没有登录并且该请求没有被放行时，就会执行该EntryPoint的commence
                //CasAuthenticationEntryPoint的实际操作就是拼接cas server url+callback url，然后进行重定向
                .authenticationEntryPoint(authenticationEntryPoint)
                .and()
                //将自定义的过滤器配置进来
                .addFilter(casAuthenticationFilter)
                .addFilterBefore(singleSignOutFilter,CasAuthenticationFilter.class)
                .addFilterBefore(logoutFilter,LogoutFilter.class);
    }
}
